package com.xyz.app.servlet;

import com.alibaba.fastjson.JSONObject;
import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.util.Config;
import com.xyz.domain.constants.EhCacheConstants;
import com.xyz.kaptcha.CalculateKaptchaServlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import java.util.UUID;

public class NoSessionCalculateKaptchaServlet extends CalculateKaptchaServlet {

    private Properties props = new Properties();

    private Producer kaptchaProducer = null;

    private String sessionKeyValue = null;

    private String sessionKeyDateValue = null;

    @Autowired
    private CacheManager cacheManager;

    public NoSessionCalculateKaptchaServlet(){
    }

    @Override
    public void init(ServletConfig conf) throws ServletException
    {
        super.init(conf);

        ServletContext application = this.getServletContext();
        // 解决servlet用@Autowired自动注入service失败的问题
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, application);

        // Switch off disk based caching.
        ImageIO.setUseCache(false);

        Enumeration<?> initParams = conf.getInitParameterNames();
        while (initParams.hasMoreElements())
        {
            String key = (String) initParams.nextElement();
            String value = conf.getInitParameter(key);
            this.props.put(key, value);
        }

        Config config = new Config(this.props);
        this.kaptchaProducer = config.getProducerImpl();
        this.sessionKeyValue = config.getSessionKey();
        this.sessionKeyDateValue = config.getSessionDate();
    }

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException
    {
//        // Set to expire far in the past.
//        resp.setDateHeader("Expires", 0);
//        // Set standard HTTP/1.1 no-cache headers.
//        resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
//        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
//        resp.addHeader("Cache-Control", "post-check=0, pre-check=0");
//        // Set standard HTTP/1.0 no-cache header.
//        resp.setHeader("Pragma", "no-cache");

        String tokenStr = String.format("TK%s", UUID.randomUUID().toString());

        // return a jpeg
        //resp.setContentType("image/jpeg");

        // create the text for the image
        String capText = this.kaptchaProducer.createText();

        cacheManager.getCache(EhCacheConstants.TokenKaptchaCache).put(tokenStr,calculateVal(capText));

        // store the text in the session
        //req.getSession().setAttribute(this.sessionKeyValue, calculateVal(capText));
        // store the date in the session so that it can be compared
        // against to make sure someone hasn't taken too long to enter
        // their kaptcha
        //req.getSession().setAttribute(this.sessionKeyDateValue, new Date());

        // create the image with the text
        BufferedImage bi = this.kaptchaProducer.createImage(capText);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        // write the data out
        ImageIO.write(bi, "jpg", outputStream);

        BASE64Encoder encoder = new BASE64Encoder();
        String base64Img = "data:image/png;base64," + encoder.encode(outputStream.toByteArray());

        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json; charset=utf-8");
        PrintWriter writer = resp.getWriter();
        JSONObject o = new JSONObject();
        o.put("token",tokenStr);
        o.put("png",base64Img);
        writer.write(o.toJSONString());
    }

}
